<?php
/* Reminder: always indent with 4 spaces (no tabs). */
// +---------------------------------------------------------------------------+
// |  グループ別カテゴリ別件数一覧、カテゴリ別一覧
// +---------------------------------------------------------------------------+
// $Id: public_html/userbox/category_group.php
//define ('THIS_SCRIPT', 'userbox/category_group.php');
define ('THIS_SCRIPT', 'userbox/category2.php');

define ('NEXT_SCRIPT', 'userbox/profile.php');
//define ('THIS_SCRIPT', 'userbox/test.php');
//20110927 tsuchitani AT ivywe DOT co DOT jp http://www.ivywe.co.jp/
//20110927

require_once ('../lib-common.php');
if (!in_array('userbox', $_PLUGINS)) {
    echo COM_refresh($_CONF['site_url'] . '/index.php');
    exit;
}

$perpage=$_USERBOX_CONF['perpage']; // 1ページの行数 @@@@@

//debug 時 true
$_USERBOX_VERBOSE = false;
$_USERBOX_VERBOSE = true;

// +---------------------------------------------------------------------------+
// | 機能  グループ別カテゴリ別件数一覧表示
// | 書式
// +---------------------------------------------------------------------------+
// | 引数　$template　使用するテンプレートフォルダの名前
// | 戻値
// +---------------------------------------------------------------------------+
function fnclist($pi_name,$template,$group_id="")
{
    global $_CONF;
    global $_TABLES;
    global $_USERBOX_CONF;
    global $perpage;
    global $LANG_USERBOX;
    global $LANG_USERBOX_ADMIN;
	
    //-----
    $page = COM_applyFilter($_REQUEST['page'],true);
    if (!isset($page) OR $page == 0) {
        $page = 1;
    }

    //-----
    $tbl1=$_TABLES['USERBOX_category'] ;
    $tbl2=$_TABLES['USERBOX_base'] ;
    $tbl3=$_TABLES['USERBOX_def_category'] ;
    $tbl4=$_TABLES['USERBOX_def_group'] ;//@@@@@

    //-----
    $sql = "SELECT ".LB;

    $sql .= " t1.category_id ".LB;
    $sql .= " ,t3.name ".LB;
    $sql .= " ,t3.code ".LB;
    $sql .= " ,t3.description ".LB;
    $sql .= " ,Count(t1.id) AS count".LB;
    $sql .= " ,t4.name AS group_name ".LB;

    $sql .= " FROM ".LB;
    $sql .= " {$tbl1} AS t1 ".LB;
    $sql .= " ,{$tbl2} AS t2 ".LB;
    $sql .= " ,{$tbl3} AS t3 ".LB;
    $sql .= " ,{$tbl4} AS t4 ".LB;

    $sql .= " WHERE ".LB;
    $sql .= " t1.id = t2.id ".LB;
    $sql .= " AND t1.category_id = t3.category_id ".LB;
	if ($group_id<>""){
		$sql .= " AND t3.categorygroup_id = ".$group_id.LB;
	}
	$sql .= " AND t3.categorygroup_id = t4.group_id ".LB;
    //管理者の時,下書データも含む
    //if ( SEC_hasRights('userbox.admin')) {
    //}else{
       $sql .= " AND t2.draft_flag=0".LB;
    //}
    //アクセス権のないデータ はのぞく
    $sql .= COM_getPermSql('AND',0,2,"t2").LB;
    //公開日以前のデータはのぞく
    $sql .= " AND (released <= NOW())".LB;

    //公開終了日を過ぎたデータはのぞく
    $sql .= " AND (expired=0 OR expired > NOW())".LB;

    $sql .= " GROUP BY ".LB;
    $sql .= " t1.category_id".LB;

    $sql .= " ORDER BY ".LB;
    $sql .= " t4.orderno,t3.orderno".LB;


    $result = DB_query ($sql);
    $cnt = DB_numRows ($result);
	
    $pages = 0;
    if ($perpage > 0) {
        $pages = ceil($cnt / $perpage);
    }
    //ヘッダ、左ブロック
    if ($page > 1) {
        $page_title = sprintf ('%s (%d)', $LANG_USERBOX['category_top'], $page);
    } else {
        $page_title = sprintf ('%s ', $LANG_USERBOX['category_top']);
    }
    $headercode="<title>".$_CONF['site_name']." - ".$page_title ."</title>";
    $retval .= DATABOX_siteHeader($pi_name,'',$page_title,$headercode);

    //

    $tmplfld=DATABOX_templatePath('category',$template,$pi_name);
    $templates = new Template($tmplfld);
    $templates->set_file (array (
        'list' => 'list.thtml',
        'nav'   => 'navigation.thtml',
        'row'   => 'row.thtml',
        'col'   => "col.thtml",
        'grp'   => "grp.thtml",
        'pagenav'  => 'pagenavigation.thtml'
        ));


    //
    $templates->set_var ('site_url',$_CONF['site_url']);
    $templates->set_var ('this_script',THIS_SCRIPT);

    $templates->set_var ('home',$LANG_USERBOX['home']);
    $templates->set_var ('lang_category_list_h2',$LANG_USERBOX['category_top']);

    //page
    $offset = ($page - 1) * $perpage;
    $lin1=$offset+1;
    $lin2=$lin1+$perpage - 1;
    if ($lin2>$cnt){
        $lin2=$cnt;
    }
    $templates->set_var ('lang_view', $LANG_USERBOX['view']);
    $templates->set_var ('lin', $lin1."-".($lin2));
    $templates->set_var ('cnt', $cnt);

    //
    $templates->set_var ('lang_name', $LANG_USERBOX_ADMIN['name']);
    $templates->set_var ('lang_count', $LANG_USERBOX['count']);

    //

    $sql .= " LIMIT $offset, $perpage";

    $result = DB_query ($sql);
    $numrows = DB_numRows ($result);
	$old_group_name="";
    if ($numrows > 0) {
        for ($i = 0; $i < $numrows; $i++) {
            $A = DB_fetchArray ($result);
			
			$group_name=COM_applyFilter($A['group_name']);

            $name=COM_applyFilter($A['name']);
            $description=COM_applyFilter($A['description']);
            $url=$_CONF['site_url'] . "/".THIS_SCRIPT;
            $url.="?";
            //コード使用の時
            if ($_USERBOX_CONF['categorycode']){
                $url.="m=code";
                $url.="&code=".$A['code'];
            }else{
                $url.="m=id";
                $url.="&id=".$A['category_id'];
            }
            $url = COM_buildUrl( $url );
            $link= COM_createLink($name, $url);
            $templates->set_var ('category_link', $link);
            $templates->set_var ('category_name', $name);
            $templates->set_var ('category_description', $description);
            $templates->set_var ('category_url', $url);
            $templates->set_var ('count', $A['count']);

            //=====
			if ($old_group_name<>$group_name){
				$templates->set_var ('group_name', $group_name);
				$templates->parse ('grp_var', 'grp', true);
				$old_group_name=$group_name;
			}
			$templates->parse ('col_var', 'col', true);
            $templates->parse ('row_var', 'row', true);

            $templates->set_var ('grp_var', '');
            $templates->set_var ('col_var', '');

        }
        //ページなび
        //$url = $_CONF['site_url']  . '/'.THIS_SCRIPT."?m=".$m;//."?order=$order";
        $url = $_CONF['site_url']  . '/'.THIS_SCRIPT;

        $templates->set_var ('page_navigation',
                  COM_printPageNavigation ($url, $page, $pages));
        //------------
        $templates->parse ('nav_var', 'nav', true);

        $templates->set_var ('blockfooter',COM_endBlock());

        $templates->set_var ('msg', "");

        $templates->parse ('output', 'list');

        $school_content = $templates->finish ($templates->get_var ('output'));
        $retval .=$school_content;

    }else{
        $templates->set_var ('msg', $LANG_USERBOX["nohit"]);
        $templates->parse ('output', 'list');
        $content = $templates->finish ($templates->get_var ('output'));
        $retval .=$content;
    }

    $retval =PLG_replacetags ($retval);

    return $retval;
}


function test_category(
    $autotag
    ,$category_id=null
    ,$template=null
    ,$nohitmsg=""
    ,$perpage =0
    ,$page=null
    ,$order=null
    ,$category_code=null
)
{

    $pi_name="userbox";

    global $_CONF;
    global $_TABLES;

    global $_USERBOX_CONF;
    global $LANG_USERBOX;
    global $LANG_USERBOX_ADMIN;
	global  $LANG28;
	
	//ログイン要否チェック
    if (COM_isAnonUser()){
        if  ($_CONF['loginrequired']
                OR ($_USERBOX_CONF['loginrequired'] >1) ){
            return $LANG_USERBOX['loginrequired'];
        }

    }

    //-----テーブル
    $tbl1=$_TABLES['USERBOX_category'] ;
    $tbl2=$_TABLES['USERBOX_base'] ;
    $tbl3=$_TABLES['USERBOX_addition'] ;
    $tbl4=$_TABLES['users'] ;
    $tbl5=$_TABLES['USERBOX_def_category'] ;

    //-----引数チェック
    if (is_null($category_id)){
        if ($category_code<>""){
            $category_id=DATABOX_codetoid($category_code,'USERBOX_def_category',"category_id");

        }
    }
    if (is_null($page)){
        $page=1;
    }
    $datefield=$_USERBOX_CONF['datefield'];//使用する日付（編集日付、作成日付）

    if ($perpage===0 OR is_null($perpage)){
        $perpage=$_USERBOX_CONF['perpage'];
    }

    if (is_null($category_id)) {
        $category_id=0;
    }
    $w=userbox_orderby($datefield,$order,$orderby,$addfieldorder);

    //-----ページ
    if (!isset($page) OR $page == 0) {
        $page = 1;
    }
    $category_name="";
    $category_code="";
    $defaulttemplatesdirectory = "";
	if ($category_id<>0){
		$sql = "SELECT ";
		$sql .= " name ".LB;
		$sql .= " ,code ".LB;
		$sql .= " ,description ".LB;
		$sql .= " ,defaulttemplatesdirectory".LB;
	    $sql .= " FROM ".LB;
		$sql .= " {$tbl5} AS t5 ".LB;
		$sql .= " WHERE ".LB;
        $sql .= " t5.category_id = ".$category_id.LB;
		
		$result = DB_query ($sql);
		$numrows = DB_numRows ($result);
		if ($numrows > 0) {
            $A = DB_fetchArray ($result);
			$category_name=COM_applyFilter($A['name']);
			$category_code=COM_applyFilter($A['code']);
			$category_description=COM_applyFilter($A['description']);
			$defaulttemplatesdirectory=COM_applyFilter($A['defaulttemplatesdirectory']);
		}
    }

    if (is_null($template) or ($template==="")){
        if ($defaulttemplatesdirectory===""){
            $template="default";
        }else{
            $template=$defaulttemplatesdirectory;
        }
    }


    //-----

    $sql = "SELECT ";

    $sql .= " t2.id ".LB;
    $sql .= " ,t2.description ".LB;
    $sql .= " ,t2.".$datefield." AS datefield ".LB;

    $sql .= " ,t2.group_id";
    $sql .= " ,t2.owner_id";

    $sql .= " ,t4.username";
    $sql .= " ,t4.fullname";
    $sql .= " ,t4.photo";

    if ($addfieldorder){
        $sql .= " ,t3.value ".LB;
    }
	
	
	
	
    $sql .= " FROM ".LB;
    $sql .= " {$tbl2} AS t2 ".LB;
    $sql .= " ,{$tbl4} AS t4 ".LB;

    if ($category_id<>0){
        $sql .= " ,{$tbl1} AS t1 ".LB;
    }
    if ($addfieldorder){
        $sql .= " ,{$tbl3} AS t3 ".LB;
    }

    $sql .= " WHERE ".LB;
    if ($category_id==0){
        $sql .= " t2.id=t4.uid ".LB;
    }else{
        $sql .= " t1.category_id = ".$category_id.LB;
        $sql .= " AND t2.id=t4.uid ".LB;
        $sql .= " AND t1.id = t2.id ".LB;
    }

    if ($addfieldorder){
        $sql .= " AND t3.field_id=".$field_id.LB;
        $sql .= " AND t3.id=t2.id".LB;
    }

	//管理者の時,下書データも含む
	//20110529 delete
    //if ( SEC_hasRights('userbox.admin')) {
    //}else{
       $sql .= " AND t2.draft_flag=0".LB;
    //}

    //アクセス権のないデータ はのぞく
    $sql .= COM_getPermSql('AND',0,2,"t2");

    //公開日以前のデータはのぞく
    $sql .= " AND (released <= NOW())".LB;
    //公開終了日を過ぎたデータはのぞく
    $sql .= " AND (expired=0 OR expired > NOW())";



    $sql .= " ORDER BY ".LB;
    $sql .= $orderby.LB;
echo "sql=".$sql."<br>";
    $result = DB_query ($sql);
    $cnt = DB_numRows ($result);

    $pages = 0;
     if ($perpage > 0) {
        $pages = ceil($cnt / $perpage);
    }

    //ヘッダ、左ブロック
    if ($autotag==="notautotag"){
        if ($page > 1) {
            $page_title = sprintf ('%s (%d)', $category_name, $page);
        } else {
            $page_title = sprintf ('%s ', $category_name);
        }
        $headercode="<title>".$_CONF['site_name']." - ".$page_title ."</title>";
        $retval .= DATABOX_siteHeader($pi_name,'',$page_title);
    }

    $tmplfld=DATABOX_templatePath('category',$template,$pi_name);
    $templates = new Template($tmplfld);
    $templates->set_file (array (
        'list' => 'list_detail.thtml',
        'nav'   => 'navigation_detail.thtml',
        'row'   => 'row.thtml',
        'col'   => "col_detail.thtml",
        'pagenav'  => 'pagenavigation.thtml'
        ));


    //
    $templates->set_var ('site_url',$_CONF['site_url']);
    $templates->set_var ('this_script',THIS_SCRIPT);

    //bread
    $templates->set_var ('home',$LANG_USERBOX['home']);

    $url=$_CONF['site_url']."/userbox/category.php";
    $category_top=":<a href='".$url."'>".$LANG_USERBOX['category_top']."</a>";
    $templates->set_var ('category_top',$category_top);

    $templates->set_var ('lang_category_list_h2',$LANG_USERBOX['category_list_h2']);

    $templates->set_var ('category_name',$category_name);
    $templates->set_var ('category_code',$category_code);
    $templates->set_var ('category_description',$category_description);
	

    //page
    $offset = ($page - 1) * $perpage;
    $templates->set_var ('cnt', $cnt);
    $lin1=$offset+1;
    $lin2=$lin1+$perpage - 1;
    if ($lin2>$cnt){
        $lin2=$cnt;
    }

    //summary navigation
    $templates->set_var ('lang_view', $LANG_USERBOX['view']);
    $templates->set_var ('lin', $lin1."-".($lin2));
    $templates->set_var ('cnt', $cnt);

    $templates->set_var ('lang_name', $LANG_USERBOX_ADMIN['name']);

    $templates->set_var ('lang_username', $LANG_USERBOX_ADMIN['username']);
    $templates->set_var ('lang_id', $LANG_USERBOX_ADMIN['id']);
    $templates->set_var ('lang_uid', $LANG28[2]);
    $templates->set_var ('lang_username', $LANG28[3]);
    $templates->set_var ('lang_fullname',$LANG28[4]);

    //
    $templates->set_var ('lang_date', $LANG_USERBOX_ADMIN[$datefield]);

    $templates->set_var ('lang_description', $LANG_USERBOX_ADMIN['description']);
    $templates->set_var ('lang_addfield', $addfield_name);
    // 追加項目のヘッダ
    $addition_def=DATABOX_getadditiondef($pi_name);
    //

    $sql .= " LIMIT $offset, $perpage";

    $result = DB_query ($sql);
    $numrows = DB_numRows ($result);

    if ($numrows > 0) {
        for ($i = 0; $i < $numrows; $i++) {
            $A = DB_fetchArray ($result);

            $description=COM_applyFilter($A['description']);
            $username=COM_applyFilter($A['username']);
            $fullname=COM_applyFilter($A['fullname']);
            $id=COM_applyFilter($A['id']);
            $datefield=COM_applyFilter($A['datefield']);
            $value=COM_applyFilter($A['value']);

            $url=$_CONF['site_url'] . "/userbox/profile.php";
            $url.="?";
            //コード使用の時
            if ($_USERBOX_CONF['datacode']){
                $url.="m=code";
                $url.="&code=".$A['username'];
            }else{
                $url.="m=id";
                $url.="&id=".$A['id'];
            }
            $url = COM_buildUrl( $url );
            $link= COM_createLink($username, $url);


            $templates->set_var ('data_link', $link);

            $templates->set_var ('fullname', $A['fullname']);

            $templates->set_var ('data_username', $username);

            $templates->set_var ('data_description', $description);
            $templates->set_var ('data_id', $id);
            $templates->set_var ('data_url', $url);
            $templates->set_var ('data_datefield', $datefield);
			$templates->set_var ('data_value', $value);
			
			//
			
		    if (isset($A['photo']) && empty($A['photo'])) {
				$A['photo'] = '(none)'; // user does not have a photo
				$templates->set_var('data_photo', "");
			}else{
				$templates->set_var('data_photo', $A['photo']);
			}
			$photo = USER_getPhoto($uid, $A['photo'], $A['email'], -1);
			$templates->set_var('data_user_photo', $photo);


            //追加項目
            $group_id = stripslashes($A['group_id']);
            $owner_id = stripslashes($A['owner_id']);
            $chk_user=DATABOX_chkuser($group_id,$owner_id,"userbox.admin");
            $additionfields = DATABOX_getadditiondatas($id,$pi_name);
            DATABOX_getaddtionfieldsDisp($additionfields,$addition_def,$templates,$chk_user,$pi_name);

            //=====
            $templates->parse ('col_var', 'col', true);
            $templates->parse ('row_var', 'row', true);

            $templates->set_var ('col_var', '');

        }

        //------------
        //-----navigation
        $url = $_CONF['site_url']  . '/';
        if ($autotag==="notautotag"){
            $url.=THIS_SCRIPT;
        }else{
            $url.="userbox/category.php";
        }
        $url .= "?m=id";
        $url .= "&id=".$category_id;
        $url .= "&template=".$template;
        $url .= "&order=";
        //-----order navigation
        userbox_order ($url, $templates, $order) ;
        //-----page navigation
        $url .= $order;
        $templates->set_var ('page_navigation',
                COM_printPageNavigation ($url, $page, $pages));
        if ($order==="random"){
            $templates->set_var ( 'pagenavinone', 'style="display:none;"' );
        }else{
            $templates->set_var ( 'pagenavinone', '' );
        }
        //------------
        $templates->parse ('nav_var', 'nav', true);

        $templates->set_var ('blockfooter',COM_endBlock());

        $templates->set_var ('msg', "");
        //@@@@@@@@$templates->set_var ('search_link', $LANG_USERBOX['search_link']);
        //@@@@@@@@$templates->set_var ('search_var',"");

        $templates->parse ('output', 'list');

        $content = $templates->finish ($templates->get_var ('output'));
        $retval .=$content;

    }else{
        if ($nohitmsg==="yes"){
            $templates->set_var ('msg', $LANG_USERBOX["nohit"]);
            //@@@@@@$templates->set_var ('search_link', $LANG_USERBOX['search_link']);//@@@@@
            $templates->parse ('output', 'list');
            $content = $templates->finish ($templates->get_var ('output'));
            $retval .=$content;
        }
    }

    $retval =PLG_replacetags ($retval);

    //return $dbg.$retval;
    return $retval;
}

// +---------------------------------------------------------------------------+
// MAIN
// +---------------------------------------------------------------------------+
//############################
$pi_name    = 'userbox';
//############################
if  ($_USERBOX_VERBOSE){ 
	$_CONF['url_rewrite']=0;
}	
//引数
if ($_CONF['url_rewrite']){
    COM_setArgNames(array('m','arg','template','arg2'));
    $m=COM_applyFilter(COM_getArgument('m'));

    if ($m==="code"){
        COM_setArgNames(array('m','code','template','arg2'));
        $id=0;
        $code=COM_applyFilter(COM_getArgument('code'));
		$gid="";
		$gcode="";
	}else if ($m==="id"){
        COM_setArgNames(array('m','id','template','arg2'));
        $id=COM_applyFilter(COM_getArgument('id'),true);
        $code="";
		$gid="";
		$gcode="";
    }else if ($m==="gcode"){
        COM_setArgNames(array('m','gcode','template','arg2'));
        $gid="";
        $gcode=COM_applyFilter(COM_getArgument('gcode'));
		$id=0;
		$code="";
    }else if ($m==="gid"){
        COM_setArgNames(array('m','gid','template','arg2'));
        $gid=COM_applyFilter(COM_getArgument('gid'),true);
        $gcode="";
		$id=0;
		$code="";
	}else{
        $gid=0;
        $gcode="";
		$id=0;
		$code="";
    }
    $template=COM_applyFilter(COM_getArgument('template'));
    $page = COM_applyFilter($_REQUEST['page'],true);
    $order = COM_applyFilter($_REQUEST['order']);
}else{
    $gid = COM_applyFilter($_REQUEST['gid']);
    $gcode = COM_applyFilter($_REQUEST['gcode']);
    $id = COM_applyFilter($_REQUEST['id'],true);
    $code = COM_applyFilter($_REQUEST['code']);
    $template = COM_applyFilter($_REQUEST['template']);
    $page = COM_applyFilter($_REQUEST['page'],true);
    $order = COM_applyFilter($_REQUEST['order']);
}

if ($gid===""){
    if ($gcode<>""){
        $gid=DATABOX_codetoid(
			$gcode,'USERBOX_def_group',"group_id");
    }
}
if ($id===0){
    if ($code<>""){
        $id=DATABOX_codetoid(
            $code,'USERBOX_def_category',"category_id");
    }
}

echo  "gid=".   $gid."<br>";
echo  "gcode=".       $gcode."<br>";
echo  "id=".       $id."<br>";
echo  "code=".       $code."<br>";
echo  "template=".       $template."<br>";
echo  "page=".       $page."<br>";
echo  "order=".       $order."<br>";

//
$display = '';
$page_title=$LANG_USERBOX_ADMIN['piname'];

//ログイン要否チェック
if (COM_isAnonUser()){
    if  ($_CONF['loginrequired']
            OR ($_USERBOX_CONF['loginrequired'] === 3)
            OR ($_USERBOX_CONF['loginrequired'] === 2 AND $id>0) ){
        $display .= DATABOX_siteHeader($pi_name,'',$page_title);
        $display .= SEC_loginRequiredForm();
        $display .= DATABOX_siteFooter($pi_name);
        COM_output($display);
        exit;
    }

}


if ($id===0) { //一覧
	$display .= fnclist($pi_name,$template,$gid);
}else{//詳細
	//$display .= userbox_category("notautotag",$id,$template,"yes",$perpage,$page,$order,$code);
	$display .= test_category("notautotag",$id,$template,"yes",$perpage,$page,$order,$code);
}

$display .= DATABOX_siteFooter($pi_name);

//---

COM_output($display);

?>